//
//  WNReadRecView.swift
//  WalkNovel
//
//  Created by Kevin on 2023/9/15.
//

import UIKit
import JXBanner

class WNReadRecView: UIView {
    
    static let shared = WNReadRecView()
    
    lazy var bgView: UIView = {
        let view = UIView.init(frame: CGRect.zero)
        view.backgroundColor = .white
        view.wn_cornerWithBorder(20)
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = .wn_font(name: .bold, size: 18)
        label.text = "Don't Leave!"
        return label
    }()
    
    lazy var subLabel: UILabel = {
        let label = UILabel()
        label.font = .wn_font(name: .bold, size: 14)
        label.text = "Stories with a similar style"
        return label
    }()
    
    lazy var closeBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setImage(UIImage(named: "login_close"), for: .normal)
        btn.rx.tap.bind { [weak self] in
            hidenLibRec()
            (wn_getTopVC() as? WNReadVC)?.stopReadTimer()
        }.disposed(by: rx.disposeBag)
        return btn
    }()
    
    lazy var bannerView: JXBanner = {
        let view = JXBanner()
        view.placeholderImgView.image = UIImage(named: "placeholder_cover_ver")
        view.indentify = "linearBanner"
        view.delegate = self
        view.dataSource = self
        return view
    }()
    
    lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = .wn_font(name: .bold, size: 16)
        label.numberOfLines = 0
        return label
    }()
    
    lazy var desLabel: UILabel = {
        let label = UILabel()
        label.font = .wn_font(name: .bold, size: 12)
        label.numberOfLines = 4
        return label
    }()
    
    lazy var readBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setTitle("READ NOW", for: .normal)
        btn.titleLabel?.font = .wn_font(name: .bold, size: 16)
        btn.rx.tap.bind { [weak self] in
            self?.handleChooseBook(self?.recArr[self?.currentSel ?? 0].bookId ?? "")
        }.disposed(by: rx.disposeBag)
        btn.wn_cornerWithBorder(22)
        return btn
    }()
    
    var recArr = [BookDetailModel]() {
        didSet {
            darkModeConfig()
            bannerView.reloadView()
        }
    }
    
    var currentSel = 0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .init(white: 0, alpha: 0.55)
        addSubview(bgView)
        bgView.addSubview(titleLabel)
        bgView.addSubview(subLabel)
        bgView.addSubview(closeBtn)
        bgView.addSubview(bannerView)
        bgView.addSubview(nameLabel)
        bgView.addSubview(desLabel)
        bgView.addSubview(readBtn)
        bgView.snp.makeConstraints { (make) in
            make.height.equalTo(TabBarMargin+scaleWidth(262)+265)
            make.left.right.bottom.equalTo(0)
        }
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(16)
            make.left.equalTo(12)
        }
        subLabel.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(4)
            make.left.equalTo(12)
        }
        closeBtn.snp.makeConstraints { (make) in
            make.top.equalTo(16)
            make.right.equalTo(-12)
            make.width.height.equalTo(36)
        }
        bannerView.snp.makeConstraints { (make) in
            make.top.equalTo(subLabel.snp.bottom).offset(12)
            make.left.right.equalTo(0)
            make.height.equalTo(scaleWidth(262))
        }
        nameLabel.snp.makeConstraints { (make) in
            make.top.equalTo(bannerView.snp.bottom).offset(12)
            make.left.equalTo(12)
            make.right.equalTo(-12)
        }
        desLabel.snp.makeConstraints { (make) in
            make.left.equalTo(nameLabel.snp.left)
            make.top.equalTo(nameLabel.snp.bottom).offset(6)
            make.right.equalTo(-12)
        }
        readBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-TabBarMargin-12)
            make.width.equalTo(scaleWidth(240))
            make.height.equalTo(44)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension WNReadRecView: JXBannerDataSource, JXBannerDelegate {
    
    // 注册重用Cell标识
    func jxBanner(_ banner: JXBannerType) -> (JXBannerCellRegister) {
        return JXBannerCellRegister(type: JXBannerCell.self, reuseIdentifier: "LinearBannerCell")
    }
    
    // 轮播总数
    func jxBanner(numberOfItems banner: JXBannerType) -> Int {
        return recArr.count
    }
    
    // 轮播cell内容设置
    func jxBanner(_ banner: JXBannerType, cellForItemAt index: Int, cell: UICollectionViewCell) -> UICollectionViewCell {
        let tempCell = cell as! JXBannerCell
        tempCell.wn_cornerWithBorder(8)
        tempCell.msgBgView.isHidden = true
        tempCell.imageView.contentMode = .scaleAspectFill
        tempCell.imageView.wn_setupImg(recArr[index].coverUrl, placeHolder: "placeholder_cover_ver")
        tempCell.imageView.wn_cornerWithBorder(8)
        return tempCell
    }
    
    // banner基本设置（可选）
    func jxBanner(_ banner: JXBannerType, params: JXBannerParams) -> JXBannerParams {
        params.isShowPageControl = false
        return params.timeInterval(3).cycleWay(.forward)
    }
    
    // banner基本设置（可选）
    func jxBanner(_ banner: JXBannerType, layoutParams: JXBannerLayoutParams) -> JXBannerLayoutParams {
        return layoutParams.layoutType(JXBannerTransformLinear()).itemSize(CGSize(width: scaleWidth(169), height: scaleWidth(262))).itemSpacing(12).rateOfChange(0.9).minimumScale(0.8).rateHorisonMargin(0.5).minimumAlpha(0.8)
    }
    
    public func jxBanner(_ banner: JXBannerType, didSelectItemAt index: Int) {
        handleChooseBook(recArr[index].bookId ?? "")
    }
    
    // 最中心显示cell 索引
    func jxBanner(_ banner: JXBannerType, center index: Int) {
        currentSel = index
        let m = recArr[index]
        nameLabel.text = m.name
        desLabel.text = m.des
    }
    
    func handleChooseBook(_ bookId: String) {
        hidenReadRec()
        wn_getTopVC()?.wn_pushBookVC(bookId)
    }
    
    func darkModeConfig() {
        bgView.backgroundColor = isDark() ? .init(named: "black_121212") : .white
        titleLabel.textColor = isDark() ? .init(named: "gray_777777") : .black
        subLabel.textColor = isDark() ? .init(named: "gray_666666") : .init(named: "gray_999999")
        closeBtn.setImage(UIImage(named: isDark() ? "rate_close" : "login_close"), for: .normal)
        nameLabel.textColor = isDark() ? .init(named: "gray_777777") : .black
        bannerView.backgroundColor = isDark() ? .init(named: "black_121212") : .white
        desLabel.textColor = isDark() ? .init(named: "gray_666666") : .init(named: "gray_999999")
        readBtn.backgroundColor = isDark() ? .init(named: "red_A15F73") : WNColor.Fade().left2right(.init(width: scaleWidth(240), height: 44))
        readBtn.setTitleColor(isDark() ? .init(named: "red_D0AFB9") : .white, for: .normal)
        layoutIfNeeded()
    }
}

func showReadRec(_ recArr: [BookDetailModel]?) {
    if let arr = recArr, arr.count > 0 {
        WNReadRecView.shared.frame = .init(x: 0, y: 0, width: ScreenW, height: ScreenH)
        WNReadRecView.shared.recArr = arr
        wn_getTopVC()?.view.addSubview(WNReadRecView.shared)
    }
}

func hidenReadRec() {
    WNReadRecView.shared.removeFromSuperview()
}
